/*
    Android Asynchronous Http Client
    Copyright (c) 2011 James Smith <james@loopj.com>
    http://loopj.com

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.stdroom.hellomyfriend.http;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;

import android.os.Message;

/**
 * Used to intercept and handle the responses from requests made using
 * {@link AsyncHttpClient}. Receives response body as byte array with a
 * content-type whitelist. (e.g. checks Content-Type against allowed list,
 * Content-length).
 * <p>
 * For example:
 * <p>
 * 
 * <pre>
 * AsyncHttpClient client = new AsyncHttpClient();
 * String[] allowedTypes = new String[] { &quot;image/png&quot; };
 * client.get(&quot;http://www.example.com/image.png&quot;, new BinaryHttpResponseHandler(
 * 		allowedTypes) {
 * 	&#064;Override
 * 	public void onSuccess(byte[] imageData) {
 * 		// Successfully got a response
 * 	}
 * 
 * 	&#064;Override
 * 	public void onFailure(Throwable e, byte[] imageData) {
 * 		// Response failed :(
 * 	}
 * });
 * </pre>
 */
public class FileHttpResponseHandler extends AsyncHttpResponseHandler {

	// filePath
	private String mFilePath;
	
	/**
	 * Creates a new BinaryHttpResponseHandler
	 */
	public FileHttpResponseHandler() {
		super();
	}

	/**
	 * Creates a new BinaryHttpResponseHandler, and overrides the default
	 * allowed content types with passed String array (hopefully) of content
	 * types.
	 */
	public FileHttpResponseHandler(String filePath) {
		this();
		mFilePath = filePath;
	}

	//
	// Callbacks to be overridden, typically anonymously
	//

	/**
	 * Fired when a request returns successfully, override to handle in your own
	 * code
	 * 
	 * @param file
	 *            he file
	 */
	public void onSuccess(File file) {
	}

	/**
	 * Fired when a request returns successfully, override to handle in your own
	 * code
	 * 
	 * @param statusCode
	 *            the status code of the response
	 * @param file
	 *            the file
	 */
	public void onSuccess(int statusCode, File file) {
		onSuccess(file);
	}

	
	@Deprecated
	public void onFailure(Throwable error, File file) {
		// By default, call the deprecated onFailure(Throwable) for
		// compatibility
		onFailure(error);
	}

	//
	// Pre-processing of messages (executes in background threadpool thread)
	//

	protected void sendSuccessMessage(int statusCode, File responseFile) {
		sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[] { statusCode,
				responseFile }));
	}

	protected void sendFailureMessage(Throwable e, File responseFile) {
		sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[] { e,
				responseFile }));
	}

	//
	// Pre-processing of messages (in original calling thread, typically the UI
	// thread)
	//

	protected void handleSuccessMessage(int statusCode, File file) {
		onSuccess(statusCode, file);
	}

	protected void handleFailureMessage(Throwable e, File file) {
		onFailure(e, file);
	}

	// Methods which emulate android's Handler and Message methods
	@Override
	protected void handleMessage(Message msg) {
		Object[] response;
		switch (msg.what) {
		case SUCCESS_MESSAGE:
			response = (Object[]) msg.obj;
			handleSuccessMessage(((Integer) response[0]).intValue(),
					(File) response[1]);
			break;
		case FAILURE_MESSAGE:
			response = (Object[]) msg.obj;
			handleFailureMessage((Throwable) response[0],
					(File) response[1]);
			break;
		default:
			super.handleMessage(msg);
			break;
		}
	}

	// Interface to AsyncHttpRequest
	@Override
	void sendResponseMessage(HttpResponse response) {
		StatusLine status = response.getStatusLine();
		Header[] contentTypeHeaders = response.getHeaders("Content-Type");
		File responseFile = null;
		if (contentTypeHeaders.length != 1) {
			// malformed/ambiguous HTTP Header, ABORT!
			sendFailureMessage(new HttpResponseException(
					status.getStatusCode(),
					"None, or more than one, Content-Type Header found!"),
					responseFile);
			return;
		}
		
		try {
			responseFile = convertResponse(response);
		} catch (Exception e) {
			sendFailureMessage(e, (byte[]) null);
		}

		if (status.getStatusCode() >= 300) {
			sendFailureMessage(new HttpResponseException(
					status.getStatusCode(), status.getReasonPhrase()),
					responseFile);
		} else {
			sendSuccessMessage(status.getStatusCode(), responseFile);
		}
	}
	
	/**
	 * 转换Response </p>
	 * 
	 * 得到的是File
	 * 
	 * @param response
	 * @throws Exception
	 */
	protected File convertResponse(HttpResponse response) throws Exception {
		File file = new File(mFilePath);
		// 获取响应的实体流
		InputStream is = response.getEntity().getContent();
		try {
			writeFile(is, file);
		} finally {
			if (is != null) {
				is.close();
			}
		}
		return file;
	}

	/**
	 * 
	 * @param is
	 * @param f
	 * @throws Exception
	 */
	public void writeFile(InputStream is, File f) throws Exception {
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(f);
			BufferedOutputStream bos = new BufferedOutputStream(os);
			int len;
			byte[] buffer = new byte[1024];
			while ((len = is.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			bos.flush();
			bos.close();
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}
}